import axios, {AxiosRequestHeaders, AxiosResponse} from "axios";
// @ts-ignore
import MD5 from "js-md5";
// @ts-ignore
import qs from 'qs';
import {MessagePlugin} from "tdesign-vue-next";
import reqCfg from "../config/request";
import {getDefaultStore} from "../store/modules/default";
import NotificationPlugin from "tdesign-vue-next/es/notification/plugin";

const env = import.meta.env.MODE || 'development';
const cfg = env === 'development' ? reqCfg.development : reqCfg.release

const http = axios.create({
    baseURL: cfg.host,
    timeout: cfg.timeout,
})

const defaultStore = getDefaultStore()

//请求拦截
http.interceptors.request.use((cfg) => {
    if (defaultStore.Token != "") {
        // @ts-ignore
        cfg.headers["Authorization"] = `Bearer ${defaultStore.Token}`;
    }
    // @ts-ignore
    cfg.headers["Sign"] = MD5(`${defaultStore.Token}__${cfg.url}`);
    return cfg
})

//响应拦截
http.interceptors.response.use(async (res) => {
    if (res.data.code == 200) {
        return res.data.data
    } else if (res.data.code == undefined) {
        return res.data
    } else {
        if (res.data.code == 401) {
            defaultStore.updateToken("")
            await NotificationPlugin.error({
                title: '身份失效',
                content: '请重新登录账号'
            })
        } else {
            await MessagePlugin.error(res.data.msg)
        }
        return null
    }
}, async (err) => {
    if (err.response && err.response.status) {
        await MessagePlugin.error({content: err.response.status + ''})
        return null
    }
    return null
})

export type Headers = Record<string, any>

export interface Resp {
    data: any, //主要数据内容
    other: any, //次要数据内容
}

export interface PromiseResp extends AxiosResponse {
    other: any,
}

export const GetForm = (url: string, data: object, headers: Headers): Promise<PromiseResp> | Resp | null => {
    if (data == null) {
        data = {}
    }
    return http.get(url, {params: data, headers: headers})
}

export const PostForm = (url: string, data: object, headers: Headers): Promise<PromiseResp> | Resp | null => {
    if (data == null) {
        data = {}
    }
    return http.post(url, qs.stringify(data), {headers: headers})
}

export const PutForm = (url: string, data: object, headers: Headers): Promise<PromiseResp> | Resp | null => {
    if (data == null) {
        data = {}
    }
    return http.put(url, qs.stringify(data), {headers: headers})
}

export const DeleteForm = (url: string, data: object, headers: Headers): Promise<PromiseResp> | Resp | null => {
    if (data == null) {
        data = {}
    }
    return http.delete(url, {params: data, headers: headers})
}

export const PostJson = (url: string, data: object, headers: Headers): Promise<PromiseResp> | Resp | null => {
    if (data == null) {
        data = {}
    }
    headers["Content-Type"] = "application/json;charset=utf-8;";
    return http.post(url, data, {headers: headers})
}

export const PutJson = (url: string, data: object, headers: Headers): Promise<PromiseResp> | Resp | null => {
    if (data == null) {
        data = {}
    }
    headers["Content-Type"] = "application/json;charset=utf-8;";
    return http.put(url, data, {headers: headers})
}

export const GetBaseURL = () => {
    return cfg.host
}

export const GetHeaders = (url: string): AxiosRequestHeaders => {
    // @ts-ignore
    let headers: AxiosRequestHeaders = {}
    if (defaultStore.Token != "") {
        headers['Authorization'] = `Bearer ${defaultStore.Token}`
    }
    headers['Sign'] = MD5(`${defaultStore.Token}__${url}`)
    return headers
}

export default {
    GetForm, PostForm, PutForm, DeleteForm, PostJson, PutJson, GetBaseURL, GetHeaders
}